const { sqlQuery } = require('../db/mysql')
const getList = async (author, keyword) => {
  console.log(author, keyword, '---- 获取博客列表 参数 ----')
  // ps: where后接1=1,为了方便后面拼接sql语句 万一没有author和keyword,sql语句也不会报错因为1=1恒成立
  let sql = 'select * from blogs where 1=1'
  if (author) {
    sql += ` and author='${author}'`
  }
  if (keyword) {
    sql += ` and content like '%${keyword}%'`
  }
  const res = await sqlQuery(sql)
  return res
}
const getDetail = async (id) => {
  let sql = `select * from blogs where id=${id}`
  const res = await sqlQuery(sql)
  return res
}

const newBlog = async (blogData = {}) => {
  console.log(blogData, '---- 新建博客 参数 ----')
  const { title, content, createtime, author } = blogData
  let sql = `insert into blogs (title, content,createtime, author) values ('${title}', '${content}',${createtime},'${author}')`
  let res = await sqlQuery(sql)
  if (res.affectedRows > 0) {
    return blogData
  } else {
    return false
  }
}

const updateBlog = async (id, blogData = {}) => {
  const { title, content, author } = blogData
  let sql = `update blogs set title='${title}',content='${content}',author='${author}' where id=${id}`
  let res = await sqlQuery(sql)
  console.log(res, '---- 更新博客 结果 ----')
  if (res.affectedRows > 0) {
    return blogData
  } else {
    return false
  }
}

const delBlog = async (id) => {
  // 先练习真删除，实战中基本都输软删除，即数据库改变state状态为0,查询数据时只查询state=1的数据
  let sql = `delete from blogs where id=${id}`
  let res = await sqlQuery(sql)
  return res
}

module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog,
}
